05. 变量 II

练习答案:赋值和修改变量

以下是我们对之前练习提供的答案:

# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6

# decrease the rainfall variable by 10% to account for runoff
rainfall *= .9

# add the rainfall variable to the reservoir_volume variable
reservoir_volume += rainfall

# increase reservoir_volume by 5% to account for stormwater that flows
# into the reservoir in the days following the storm
reservoir_volume *= 1.05

# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume *= 0.95

# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5 

# print the new value of the reservoir_volume variable
print(reservoir_volume)

多重赋值

我们也可以在一行代码中同时为两个变量赋值:

#These two assignments can be abbreviated
savings = 514.86
salary = 320.51

#Using multiple assignment
savings, salary = 514.86, 320.51

第一个变量被赋值为 = 之后的第一个值,第二个变量则接收第二个值。对于两个紧密相关的变量,如某物体的宽度和高度、或某物体的 x 轴和 y 轴坐标,在进行赋值时我们可以使用多重赋值。

更改变量

当我们更改一个变量时,会对另一个根据其定义的变量造成怎样的影响?我们来看一个例子。

以下是马尼拉人口和人口密度的初步数据。

>>> manila_pop = 1780148
>>> manila_area = 16.56
>>> manila_pop_density = manila_pop/manila_area
>>> print(int(manila_pop_density))
107496

现在我们重新定义 manila_pop 变量:

>>> manila_pop = 1781573

变量更改

根据上面的代码,猜测这个表达式的输出是什么。
```python

print(int(manila_pop_density))
```

SOLUTION: 107496

正确的答案是 int(manila_pop_density) 的值没有改变。这是因为一个变量被赋值时,其被赋予的是 右侧表达式的值 ,而不是表达式本身。在代码行
```python

manila_pop_density = manila_pop/manila_area

Python 实际上是计算右侧表达式 `manila_pop/manila_area`,然后将该表达式的值赋值给变量 `manila_pop_density`。在将表达式的结果赋值之后,它将马上忘记这个公式。
要依据 `manila_pop` 更新 `manila_pop_density` 的值,我们需要再次运行这行代码:

manila_pop_density = manila_pop/manila_area
print(int(manila_pop_density))
107582
```
这就是考虑到人口新增和减少之后的新人口密度 —— 为了考虑到这一点,我们已经更新了所有变量。